import path from "path";
import fs from "fs";

const getDataMiddleWare = async (req, res, next) => {
  const reqestUrl = req.url;
  if (reqestUrl === "/") {
    await next();
  } else {
    const requestPath = req.path;
    const pathList = requestPath.split("/");
    const interfacePath = pathList.slice(1).join("/");
    let filePath = path.join(path.dirname(process.cwd()), "/mockData/");
    filePath = filePath.replace(/\\/g, "/");
    filePath = filePath + interfacePath + ".js";

    // 设置Content-Type为application/json; charset=utf-8
    res.setHeader("Content-Type", "application/json; charset=utf-8");

    try {
      if (fs.existsSync(filePath)) {
        const fileContent = fs.readFileSync(filePath, "utf-8");
        const data = eval(fileContent);
        res.end(JSON.stringify(data));
      } else {
        res.end(
          JSON.stringify({
            data: null,
            message: `${requestPath}接口不存在`,
            code: 200
          })
        );
      }
    } catch (error) {
      res.end(
        JSON.stringify({
          data: null,
          message: `mock数据异常,${error.toString()}`,
          code: 200
        })
      );
    } finally {
      await next();
    }
  }
};

export default getDataMiddleWare;
